package com.ynr.voucher.service.impl;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.ynr.dao.ICompanyDao;
import com.ynr.dao.ICompanyInvoiceDao;
import com.ynr.dao.IInvoiceDao;
import com.ynr.voucher.dao.IVoucherDao;
import com.ynr.voucher.model.InvoiceItemModel;
import com.ynr.voucher.model.InvoiceModel;
import com.ynr.voucher.service.IVoucherSalesService;
import com.ynr.voucher.service.IVoucherService;
import com.ynr.voucher.utils.ExcelReader;

@Service
public class VoucherSalesServiceImpl implements IVoucherSalesService {

	private static final Logger logger = LoggerFactory.getLogger(VoucherSalesServiceImpl.class);
	
	@Autowired
	private IVoucherService voucherService;
	
	@Autowired
	private IVoucherDao voucherDao;
	
	@Autowired
	private IInvoiceDao invoiceDao;
	
	@Autowired
	private ICompanyInvoiceDao companyInvoiceDao;
	
	@Autowired
	private ICompanyDao companyDao;
	
	@Override
	public void processSales(InvoiceModel invoice, Map<String, Object> companyMap) {
		String billDate = invoice.getBillDate();
		Map<String, Integer> retMap = voucherDao.getLastVoucherNum(billDate, "invoice");
		int lastVoucherNum = retMap.get("lastVoucherNum");
		logger.debug("VoucherSalesServiceImpl method processSales, lastVoucherNum : {}", lastVoucherNum);
		for(InvoiceItemModel item : invoice.getGoodsData()) {
			voucherService.generateSalesVoucher(billDate, 1, invoice, companyMap, item, lastVoucherNum);
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void processSalesExcel(String filePath, int companyId, String billDate) {
		Map<String, Object> companyMap = companyDao.getCompanyById(companyId);
		String companyName = (String)companyMap.get("name");
		List<Map<String, Object>> salesMap = ExcelReader.parseSalesExcel(filePath, companyName);
		for(Map<String, Object> sale : salesMap) {
			InvoiceModel invoice = JSON.parseObject(JSON.toJSONString(sale), InvoiceModel.class);
			List<Map<String, Object>> goodsList = (List)sale.get("goodsData");
			sale.remove("goodsData");
			invoiceDao.insertInvoiceDetailInfo(sale, filePath, 1, 1, billDate);
			invoiceDao.insertInvoiceItem(goodsList, (long)sale.get("id"));
			companyInvoiceDao.insert(companyId, (long)sale.get("id"));
			
			//写凭证
			invoice.setBillDate(billDate);
			processSales(invoice, companyMap);
		}
	}


}
